//
//  ChosenViewController.m
//  KiklinkApp
//
//  Created by LJC on 14-9-2.
//  Copyright (c) 2014年 Kiklink. All rights reserved.
//

#import "ChosenViewController.h"

#import "UIView+loadWithNib.h"
#import "UIColor+hex.h"

#import "SearchBar.h"
#import "ChosenCell.h"
#import "MJRefresh.h"

#import "API.h"

#import "SearchViewController.h"
#import "ProductViewController.h"

static NSString *ChosenTableCellIdentifier = @"ChosenCell";

@interface ChosenViewController ()
{
    //data
    NSMutableArray *chosenTableArray;
    NSInteger page;
    NSInteger totalPage;
    
    //ui
    UIBarButtonItem *searchItem;
    SearchBar *search;
    UIBarButtonItem *searchBarItem;
}
@end

@implementation ChosenViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = @"精选";
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithHexString:AppColor_BackGround];
    
    
    //loading
    [self.activity startAnimating];
    self.refreshBtn.hidden = YES;
    [self.refreshBtn addTarget:self action:@selector(refresh) forControlEvents:UIControlEventTouchUpInside];
    
    
    //rightNavItem
    searchItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(searchBarPresent)];
    searchItem.tintColor = [UIColor colorWithHexString:AppColor_Main andAlpha:0.8];
    
    search = [[SearchBar alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth*9/10, NavBarHeight)];
    search.placeholder = @"向右滑动取消";
    search.delegate = self;
    UISwipeGestureRecognizer *rightSwip = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(searchBarDismis)];
    rightSwip.direction = UISwipeGestureRecognizerDirectionRight;
    [search addGestureRecognizer:rightSwip];
    searchBarItem = [[UIBarButtonItem alloc] initWithCustomView:search];
    
    self.navigationItem.rightBarButtonItem = searchItem;
    
    
    //chosenTable
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.chosenTable.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.chosenTable.backgroundColor = [UIColor colorWithHexString:AppColor_BackGround];
    self.chosenTable.delegate = self;
    self.chosenTable.dataSource = self;
    self.chosenTable.showsVerticalScrollIndicator = NO;
    [self.chosenTable registerClass:[UITableViewCell class] forCellReuseIdentifier:ChosenTableCellIdentifier];
    [self setupRefresh];
    [self.chosenTable reloadData];
    
    
    //data
    chosenTableArray = [[NSMutableArray alloc] init];
    page = 1;
    [self getData:1 Condition:@"first"];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = NO;
    
    self.title = @"精选";
    [search resignFirstResponder];
    self.navigationItem.rightBarButtonItem = searchItem;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - get data
//condition:first&header&footer
- (void)getData:(NSInteger)pageNum Condition:(NSString *)condition
{
    NSLog(@"page:%ld",(long)pageNum);
    [API courseSearchWithKeyword:@"" distance:@0 tags:@"" category:@0 sortStyle:@"" pageNumber:[NSNumber numberWithInteger:pageNum] Callback:^(int stateCode, NSString *word, id content) {
        
        if (stateCode == SUCCESS) {
            ProductPage *productPage = (ProductPage *)content;
            NSMutableArray *result = [[NSMutableArray alloc] initWithArray:productPage.result];
            
            if ([condition isEqualToString:@"first"]) {
                totalPage = productPage.lastPageNumber;
                self.chosenTable.scrollEnabled = YES;
                page = 2;
                chosenTableArray = result;
            } else if ([condition isEqualToString:@"header"]) {
                page = 2;
                chosenTableArray = result;
            } else if ([condition isEqualToString:@"footer"]) {
                page ++;
                [chosenTableArray addObjectsFromArray:result];
            }
            
            [self loadData:condition];
            
        } else {
            if ([condition isEqualToString:@"first"]) {
                self.chosenTable.scrollEnabled = NO;
                [self.activity stopAnimating];
                self.refreshBtn.hidden = NO;
            } else if ([condition isEqualToString:@"header"]) {
                [self.chosenTable headerEndRefreshing];
            } else if ([condition isEqualToString:@"footer"]) {
                [self.chosenTable footerEndRefreshing];
            }
        }
    }];
}

- (void)loadData:(NSString *)condition
{
    [self.chosenTable reloadData];
    
    if ([condition isEqualToString:@"first"]) {
        [self.activity stopAnimating];
    } else if ([condition isEqualToString:@"header"]) {
        [self.chosenTable headerEndRefreshing];
    } else if ([condition isEqualToString:@"footer"]) {
        [self.chosenTable footerEndRefreshing];
    }
}

- (void)refresh
{
    self.refreshBtn.hidden = YES;
    [self.activity startAnimating];
    
    [self getData:1 Condition:@"first"];
}
#pragma mark - get data End

#pragma mark - searchBarPresent&dismiss&input
- (void)searchBarPresent
{
    CATransition *animation = [CATransition animation];
    animation.duration = 0.3;
    animation.type = @"push";
    animation.subtype = @"fromRight";
    
    self.title = @"";
    self.navigationItem.rightBarButtonItem = searchBarItem;
    
    [self.navigationController.navigationBar.layer addAnimation:animation forKey:nil];
    [search becomeFirstResponder];
}
- (void)searchBarDismis
{
    CATransition *animation = [CATransition animation];
    animation.duration = 0.4;
    animation.type = @"push";
    animation.subtype = @"fromLeft";
    
    self.title = @"精选";
    [search resignFirstResponder];
    self.navigationItem.rightBarButtonItem = searchItem;
    
    [self.navigationController.navigationBar.layer addAnimation:animation forKey:nil];
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    SearchViewController *searchVC = [[SearchViewController alloc] init];
    searchVC.keyWord = searchBar.text;
    [self.navigationController pushViewController:searchVC animated:YES];
}
#pragma mark - searchBarPresent&dismiss&input End

#pragma tableView dataSource&delegate  &MJRefresh
- (void)setupRefresh
{
    [self.chosenTable addHeaderWithTarget:self action:@selector(headerRereshing)];
//    [self.chosenTable headerBeginRefreshing];
    [self.chosenTable addFooterWithTarget:self action:@selector(footerRereshing)];
    
    self.chosenTable.headerPullToRefreshText = @"下拉可以刷新";
    self.chosenTable.headerReleaseToRefreshText = @"松开马上刷新";
    self.chosenTable.headerRefreshingText = @"正在刷新...";
    self.chosenTable.footerPullToRefreshText = @"上拉加载更多";
    self.chosenTable.footerReleaseToRefreshText = @"松开马上加载";
    self.chosenTable.footerRefreshingText = @"正在加载...";
}
- (void)headerRereshing
{
    //data
    [self getData:1 Condition:@"header"];
}
- (void)footerRereshing
{
    //data
    if (page <= totalPage) {
        [self getData:page Condition:@"footer"];
    } else {
        [self.chosenTable footerEndRefreshing];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return chosenTableArray.count*2;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row%2 == 0) {
        BOOL nibsRegistered = NO;
        if (!nibsRegistered) {
            UINib *nib = [UINib nibWithNibName:@"ChosenCell" bundle:nil];
            [tableView registerNib:nib forCellReuseIdentifier:ChosenTableCellIdentifier];
            nibsRegistered = YES;
        }
        ChosenCell *cell = (ChosenCell *)[tableView dequeueReusableCellWithIdentifier:ChosenTableCellIdentifier];
        [cell loadDataWithProduct:[chosenTableArray objectAtIndex:indexPath.row/2]];
        return cell;
    } else {
        static NSString *seperateCellIdentifier = @"SeperateCellIdentifier";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:seperateCellIdentifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:seperateCellIdentifier];
        }
        cell.backgroundColor = [UIColor colorWithHexString:AppColor_BackGround];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    };
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row%2 == 0) {
        return 165;
    } else return 8;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row%2 == 0) {
        ProductViewController *productVC = [[ProductViewController alloc] init];
        Product *corProduct = [chosenTableArray objectAtIndex:indexPath.row/2];
        productVC.productID = corProduct.id;
        productVC.product = corProduct;
        [self.navigationController pushViewController:productVC animated:YES];
    }
}
#pragma tableView dataSource&delegate &MJRefresh End

@end
